package engineer.clientapp.actions;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;

import engineer.clientapp.beans.Machine;
import engineer.clientapp.tools.Connector;


public class AddMachineAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		String target = null;
		ActionErrors actionErrors = new ActionErrors();
		Machine machine = (Machine)form;
		String machineName = machine.getMachineName();
		String address = machine.getAddress();
		String maxAmount = machine.getMaxAmount();
		FormFile file = machine.getFile();
		
		String filePath = "D:/Studia/Projekt Inżynierski/ClientApp/ClientApp/WebContent/images/automats";
		File folder = new File(filePath);
		if (!folder.exists()) {
			folder.mkdir();
		}
		
		String fileName = file.getFileName();
		
		try{
			if(!(machineName.equals("") || address.equals("") || maxAmount.equals(""))){
				if (!("").equals(fileName)) {
					File newFile = new File(filePath, fileName);

					if (!newFile.exists()) {
						FileOutputStream fos = new FileOutputStream(newFile);
						fos.write(file.getFileData());
						fos.flush();
						fos.close();
					}
					
					Connection connection = new Connector().getConnection();
		    		Statement statement = connection.createStatement();
		    		String query = "SELECT COUNT(*) FROM automats.machines WHERE name='"+machineName+"'";
			    	ResultSet rs = statement.executeQuery(query);
			    	rs.next();
			    	if(rs.getInt("COUNT(*)")==0){
			    		int amount=Integer.parseInt(maxAmount);
			    		int current = amount;
		    			statement.executeUpdate("INSERT INTO automats.machines (`name`, `address`, `max_amount`, `current_amount`,`image`) VALUES(\""+machineName+"\",\""+address+"\",\""+amount+"\",\""+current+"\",\""+fileName+"\");");
		    			
		    			target = "success";
		    			actionErrors.add("error",
								new ActionMessage("error.machineCreated"));
		    			rs.close();
						connection.close();
			    	}else{
			    		//maszyna istnieje
			    		rs.close();
			    		connection.close();
			    		target = "failure";
		    			actionErrors.add("error",
								new ActionMessage("error.machineExist"));
			    	}
				}else{
					//brak zdjęcia
					target = "failure";
	    			actionErrors.add("error",
							new ActionMessage("error.emptyFoto"));
				}
			}else{
				//puste pola
				target = "failure";
    			actionErrors.add("error",
						new ActionMessage("error.emptyFields"));
			}
			
			if (actionErrors.size() != 0) {
				extracted(request, actionErrors);
				return new ActionForward(mapping.getInput());
			}
			
		}catch(Exception e){
			e.printStackTrace();
			
		}
		
		
	
		return mapping.findForward(target);
	}
	
	private void extracted(HttpServletRequest request, ActionErrors actionErrors) {
		saveErrors(request, actionErrors);
	}

}
